package com.blyat.xsoft.gateway.ribbon.router.file;

import com.blyat.xsoft.gateway.ribbon.router.AbstractRouteDefinitionRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;

import java.util.Timer;
import java.util.TimerTask;


/**
 * @Auther: syh
 * @Date: 2020/8/21
 * @Description:
 */
public class FileRouteDefinitionRepository extends AbstractRouteDefinitionRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileRouteDefinitionRepository.class);
    private static final String ROUTERS_FILE = "routers.json";

    private final int taskTimerInterval = 1 * 1000;

    public FileRouteDefinitionRepository() {
        super(context -> new FileRouteDefinitionLoader(
                context.getEnvironment().getProperty("gateway.routers.file", ROUTERS_FILE)));

        // 启动一个定时器，检测配置文件是否发生变化。默认1秒一次
        checkFileIfNeedReload();
    }

    private void checkFileIfNeedReload() {
        Timer taskTimer = new Timer("loadRouters", true);

        taskTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (loader == null) return;
                if (loader.reload()) {
                    try {
                        setRouteDefinitions(loader.load());
                        publisher.publishEvent(
                                new RefreshRoutesEvent(FileRouteDefinitionRepository.this));
                    } catch (Exception e) {
                        LOGGER.error("file routers reload failed.");
                    }
                }
            }
        }, 0L, this.taskTimerInterval);
    }
}
